package ocmd

import (
	"osiris/cli"
	"osiris/core/state"
	"osiris/core/txpool"
	"osiris/dao"
	"osiris/errors"
	"osiris/logger"
	"sync"
)

// RmTxHandler 数据删除
type RmHandler struct{}

func (handler *RmHandler) Handle(inputs []string, wg *sync.WaitGroup) error {
	defer func() {
		if wg != nil {
			wg.Done()
		}
	}()

	if len(inputs) != 2 {
		return &errors.CommandInputError{
			Msg: "invalid arguments!",
		}
	}

	switch inputs[1] {

	case STATE:
		return handler.rmState()

	default:
		return &errors.CommandInputError{
			Msg: "invalid arguments!",
		}
	}
}

func (handler *RmHandler) rmState() error {
	innerWG := new(sync.WaitGroup)
	innerWG.Add(5)

	//truncate locals, accounts, localqueued, bolckHeader
	go func() {
		dao.TruncateAccounts()
		innerWG.Done()
	}()

	go func() {
		dao.TruncateLocalQueued()
		innerWG.Done()
	}()

	go func() {
		dao.TruncateLocals()
		innerWG.Done()
	}()

	go func(){
		dao.TruncateTxs()
		innerWG.Done()
	}()

	go func(){
		dao.TruncateHeaders()
		innerWG.Done()
	}()

	//state重置
	state.ResetState()

	//交易池重置
	txpool.TruncateTxPools()

	//虚拟客户端重置
	cli.ResetClient()

	//local.bf重置
	err := txpool.ResetLocalBF()
	if err != nil {
		return err
	}

	innerWG.Wait()
	logger.Println("rm state completed.")
	return nil
}

func (hadnler *RmHandler) PrintHelp() {
	logger.Println("usage: rm state")
}
